import 'package:cashbook/model/Accounts.dart';
import 'package:cashbook/utils/Commons.dart';
import 'package:cashbook/utils/manager.dart';
import 'package:cashbook/utils/time_util.dart';
import 'package:event_bus/event_bus.dart';
import 'package:flutter/material.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';

class RecordPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return RecordPageState();
  }
}

class RecordPageState extends State<RecordPage> {
  List<Accounts> list = List();
  var year = DateTime.now().year;
  var month = DateTime.now().month;
  var showHeader = true;
  var income = 0.00;
  var pay = 0.00;

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text('记账本'),
        centerTitle: true,
        leading: Text(''),
        actions: <Widget>[
          GestureDetector(
            child: Container(
              padding: const EdgeInsets.only(left: 15, right: 15),
              color: Colors.blue,
              child: Icon(
                Icons.add,
                color: Colors.white,
              ),
            ),
            onTap: () {
//              addAlertDialog(context, () {
//                addAccount();
//              });
              Navigator.of(context).pushNamed('/addaccount');
            },
          )
        ],
      ),
      body: Center(
        child: Column(
          children: <Widget>[
            Container(
              height: 50,
              margin: EdgeInsets.only(top: 0, bottom: 5),
              padding: EdgeInsets.only(left: 15, right: 15),
              color: Colors.black12,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  GestureDetector(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Text('${year}年'),
                        Row(
                          children: <Widget>[
                            Text('${month}月'),
                            Icon(Icons.arrow_drop_down)
                          ],
                        )
                      ],
                    ),
                    onTap: () {
                      selectDateAndMouth();
                    },
                  ),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Text('收入'),
                      Text('￥${income}'),
                    ],
                  ),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Text('支出'),
                      Text('￥${pay}'),
                    ],
                  )
                ],
              ),
            ),
            Expanded(
                child: ListView.builder(
                    itemCount: list.length,
                    itemBuilder: (context, index) {
                      return initItemView(context, index);
                    }))
          ],
        ),
      ),
    );
  }

  @override
  void initState() {
    getDataFromDb(year, month); //首次加载数据
    //监听器
    Manager.instance.eventBus.on().listen((data) {
      if (null != data && data.title == Commons.REFRESH_ACCOUNTS) {
        //刷新Listview
        getDataFromDb(year, month);
      }
    });
  }

  @override
  void dispose() {}

  void getDataFromDb(int year, int month) async {
    List<Accounts> listAccounts =
        await AccountsProvider().findAllAccountsByYearAndMouth(year, month);
    this.income = this.pay = 0;
    if (listAccounts.length > 0) {

      for (int i = 0; i < listAccounts.length; i++) {
        Accounts a = listAccounts[i];
        //收入
        if (a.type == 'SR') {
          double moneyTmp = a.money == null ? 0 : double.parse(a.money);
          this.income = this.income + moneyTmp;
        }
        if (a.type == 'ZC') {
          double moneyTmp = a.money == null ? 0 : double.parse(a.money);
          this.pay = this.pay + moneyTmp;
        }
      }

      setState(() {
        this.list.clear();
        this.list.addAll(listAccounts);
        this.pay;
        this.income;
      });
    }
  }

  void selectDateAndMouth() {
    DatePicker.showYearOrMouthOrDayPicker(context,
        dateType: DateType.YEAR_MOUTH, onConfirm: (date) {
      setState(() {
        this.year = date.year;
        this.month = date.month;
        getDataFromDb(year, month);
      });
    }, currentTime: DateTime.now(), locale: LocaleType.zh);
  }

  Widget initItemView(BuildContext context, int index) {
    return Container(
      child: Container(
        margin: const EdgeInsets.only(left: 10, right: 10),
        child: Column(
          children: <Widget>[
            headerView(context, index),
            Container(
              margin: EdgeInsets.only(top: 10, bottom: 10),
              child: Row(
                children: <Widget>[
                  Icon(Icons.title),
                  Expanded(flex: 1, child: Text('${list[index].title}')),
                  Text(list[index].type == 'SR'
                      ? '${(list[index].money)}'
                      : '-${(list[index].money)}')
                ],
              ),
            ),
//            Container(
//              margin: EdgeInsets.only(left: 25),
//              child: Divider(
//                height: 1,
//                color: Colors.grey,
//              ),
//            )
          ],
        ),
      ),
    );
  }

  header(BuildContext context, int index) {
    return Column(
      children: <Widget>[
        Container(
          width: double.infinity,
          alignment: Alignment.centerLeft,
          margin: EdgeInsets.only(
            bottom: 15,
            top: 15,
          ),
          child: Text(
            TimeUtil.getFormatTimestamp2('${list[index].createTime}'),
            style: TextStyle(color: Colors.grey),
          ),
        ),
        Divider(
          height: 1,
          color: Colors.grey,
        )
      ],
    );
  }

  headerView(BuildContext context, int index) {
    if (list.length == 1) {
      return header(context, index);
    } else {
      if (index == 0) {
        return header(context, index);
      } else if (index != 0 &&
          list[index].createTime != list[index - 1].createTime) {
        return header(context, index);
      }
      return Container(
        height: 0,
      );
    }
  }
}
